//
//  YYEHomePageViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2017/12/27.
//  Copyright © 2017年 胡波. All rights reserved.
//

#import "YYEHomePageViewController.h"
#import "YYEHotCourseTableViewCell.h"
#import "YYEHotClassifyTableViewCell.h"
#import "YYELatestRecommandTableViewCell.h"
#import "YYETeacherTableViewCell.h"
#import <SDCycleScrollView.h>
#import "YYECoursePlayViewController.h"
#import "YYELatestCourseViewController.h"
#import "YYEHotCourseViewController.h"
#import "YYECourseClassifyModel.h"
#import "YYEHomeCourseModel.h"
#import "YYECourseViewController.h"
#import "YYECourseSearchViewController.h"
#import "YYENaivigationController.h"
#import <PYSearch.h>
#import "YYECourseApplyViewController.h"

@interface YYEHomePageViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,PYSearchViewControllerDelegate,PYSearchViewControllerDataSource>

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) SDCycleScrollView *cycleSV;
@property (nonatomic,strong) SDCycleScrollView *titleCycleSV;
@property (nonatomic,strong) NSMutableArray *cycleArr;
@property (nonatomic,strong) NSMutableArray *broadArr;
@property (nonatomic,strong) NSMutableArray *classifyArr;
@property (nonatomic,strong) NSMutableArray *faceArr;
@property (nonatomic,strong) NSMutableArray *courseArr;
@property (nonatomic,strong) NSMutableArray *teacherArr;
@property (nonatomic,strong) NSMutableArray *hotArr;
@property (nonatomic,strong) PYSearchViewController *searchVC;

@end

@implementation YYEHomePageViewController

static NSString *hotCourseCell = @"hotCourse";
static NSString *hotClassify = @"hotClassify";
static NSString *latestRecommand = @"latestRecommand";
static NSString *teacherCell = @"teacherCell";



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configUI];
    
    [self configNavi];
    
    [self loadData];
    [self getSearch];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //    [header beginRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;

}

- (void)configNavi {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 33, 30)];
    
    UIImageView *searchIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 6, 18, 18)];
    searchIV.image = [UIImage imageNamed:@"search"];
    [contentView addSubview:searchIV];
    
    CGFloat height = 0;
    if (Device_Is_iPhoneX) {
        height = 28+15;
    }
    else {
        height = 28;

    }
    UITextField *textF = [[UITextField alloc]initWithFrame:CGRectMake(15, height, SCREEN_WIDTH - 30, 30)];
    textF.placeholder = @"请输入搜索关键词";
    textF.backgroundColor = [UIColor whiteColor];
    [textF setValue:[UIFont systemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    textF.layer.cornerRadius = 15;
//    textF.delegate = self;
    textF.leftView = contentView;
    textF.leftViewMode = UITextFieldViewModeAlways;
    textF.tintColor = [UIColor clearColor];
    [textF addTarget:self action:@selector(tapClicked) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:textF];
}

- (void)getSearch {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"token":[LoginModel shareLogin].token,
                          @"username":[LoginModel shareLogin].username,
                          };
    NSLog(@"===%@",dic);
    [SVProgressHUD show];
    [AFNHelper post:GetSearch parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {

            if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                
                NSMutableArray *arrM = [NSMutableArray array];
                for (NSDictionary *dic in responseObject[@"data"]) {
                    [arrM addObject:dic[@"content"]];
                }
                self.hotArr = arrM;
            }
            
        }
        
    } faliure:^(id error) {

        
    }];
    
}

- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"token":[LoginModel shareLogin].token,
                          @"username":[LoginModel shareLogin].username,
                          };
    NSLog(@"===%@",dic);
    [SVProgressHUD show];
    [AFNHelper post:HomePage parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            [self.cycleArr removeAllObjects];
            NSArray *adverArr = responseObject[@"data"][@"advertising"];
            for (NSInteger i = 0; i < adverArr.count; i++) {
                NSString *str = adverArr[i][@"adv_img"];
                [self.cycleArr addObject:str];
            }
            // 轮播图
            self.cycleSV.imageURLStringsGroup = self.cycleArr;
            
            NSArray *broad = responseObject[@"data"][@"broadcast"];
            for (NSInteger i = 0; i < broad.count; i++) {
                NSString *str = broad[i][@"broadcast"];
                [self.broadArr addObject:str];
            }
            self.titleCycleSV.titlesGroup = self.broadArr;
            
            self.classifyArr = [YYECourseClassifyModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"button"]];
            self.courseArr = [YYEHomeCourseModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"hot"]];
            self.faceArr = [YYELatestRecommandModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"face"]];
            self.teacherArr = [YYEHomeCourseModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"teacher"]];
            [self.tableView reloadData];
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
        [self.tableView.mj_header endRefreshing];

        
    } faliure:^(id error) {
        
        NSLog(@"===");
        [SVProgressHUD showWithStatus:ShowError];
        [SVProgressHUD dismissWithDelay:0.5];
        [self.tableView.mj_header endRefreshing];

        
    }];
    
}

- (void)configUI {

    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = [self tableHeaderView];
    
    [self.tableView registerClass:[YYEHotCourseTableViewCell class] forCellReuseIdentifier:hotCourseCell];
    [self.tableView registerClass:[YYEHotClassifyTableViewCell class] forCellReuseIdentifier:hotClassify];
    [self.tableView registerClass:[YYELatestRecommandTableViewCell class] forCellReuseIdentifier:latestRecommand];
    [self.tableView registerClass:[YYETeacherTableViewCell class] forCellReuseIdentifier:teacherCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).offset(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];

    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];

    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

- (UIView *)tableHeaderView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 54 + SCREEN_WIDTH * 0.55)];
    contentView.backgroundColor = [UIColor whiteColor];
    
    self.cycleSV = [[SDCycleScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 0.55)];
    self.cycleSV.backgroundColor = [UIColor whiteColor];
//    self.cycleSV.localizationImageNamesGroup = @[@"lunbo_1",@"lunbo_2",@"lunbo_3",@"lunbo_4"];
    [contentView addSubview:self.cycleSV];
    
    UIView *noticeView = [[UIView alloc]init];
    noticeView.layer.borderWidth = 0.5;
    noticeView.layer.borderColor = RGB(102, 102, 102).CGColor;
    noticeView.layer.cornerRadius = 3;
    [contentView addSubview:noticeView];
    noticeView.userInteractionEnabled = NO;
    
    UIImageView *noticeIV = [[UIImageView alloc]init];
    noticeIV.image = [UIImage imageNamed:@"notice"];
    [noticeView addSubview:noticeIV];
    
    UIImageView *rightIV = [[UIImageView alloc]init];
    rightIV.image = [UIImage imageNamed:@"right"];
    [noticeView addSubview:rightIV];
    
    self.titleCycleSV = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:nil placeholderImage:nil];
    self.titleCycleSV.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.titleCycleSV.titleLabelBackgroundColor = [UIColor whiteColor];
    self.titleCycleSV.titleLabelTextAlignment = NSTextAlignmentCenter;
    self.titleCycleSV.titleLabelTextColor = RGB(102, 102, 102);
    self.titleCycleSV.onlyDisplayText = YES;
    [self.titleCycleSV disableScrollGesture];
    [noticeView addSubview:self.titleCycleSV];
    self.titleCycleSV.backgroundColor = [UIColor whiteColor];
    
    NSMutableArray *titleArray = [NSMutableArray array];
    [titleArray addObject:@"最新英语课程免费发放了！"];
    [titleArray addObject:@"英语四六级开始报名了！"];
    [titleArray addObject:@"我编不下去了！"];
    self.titleCycleSV.titlesGroup = titleArray;
    
    
    [noticeView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(17);
        make.right.equalTo(contentView.right).offset(-17);
        make.top.equalTo(self.cycleSV.bottom).offset(11);
        make.height.equalTo(32);
    }];
    
    [noticeIV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(noticeView.left).offset(6);
        make.size.equalTo(CGSizeMake(17, 17));
        make.centerY.equalTo(noticeView.centerY);
    }];
    
    [rightIV makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(noticeView.right).offset(-6);
        make.size.equalTo(CGSizeMake(8, 16));
        make.centerY.equalTo(noticeView.centerY);
    }];
    
    [self.titleCycleSV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(noticeIV.right);
        make.right.equalTo(rightIV.left);
        make.top.bottom.equalTo(noticeView);
    }];
    
    return contentView;
    
}

- (NSMutableArray *)cycleArr {
    
    if (!_cycleArr) {
        _cycleArr = [NSMutableArray array];
    }
    return _cycleArr;
    
}

- (NSMutableArray *)broadArr {
    
    if (!_broadArr) {
        _broadArr = [NSMutableArray array];
    }
    return _broadArr;
    
}

- (NSMutableArray *)classifyArr {
    
    if (!_classifyArr) {
        _classifyArr = [NSMutableArray array];
    }
    return _classifyArr;
    
}

- (NSMutableArray *)faceArr {
    
    if (!_faceArr) {
        _faceArr = [NSMutableArray array];
    }
    return _faceArr;
    
}

- (NSMutableArray *)courseArr {
    
    if (!_courseArr) {
        _courseArr = [NSMutableArray array];
    }
    return _courseArr;
    
}

- (NSMutableArray *)teacherArr {
    
    if (!_teacherArr) {
        _teacherArr = [NSMutableArray array];
    }
    return _teacherArr;
    
}

#pragma mark -- UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 1;
    }else if (section == 2) {
//        return 2;
        return self.faceArr.count;
        
    }else {
        return 1;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYEHotClassifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotClassify];
        
        cell.datas = self.classifyArr;
        
        return cell;
        
    }else if (indexPath.section == 1) {
        
        YYEHotCourseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotCourseCell];
        
        cell.datas = self.courseArr;
        
        return cell;
        
    }else if (indexPath.section == 2) {
        
        YYELatestRecommandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:latestRecommand];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.model = self.faceArr[indexPath.row];
        
        return cell;
        
    }else {
        
        YYETeacherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:teacherCell];
        cell.datas = self.teacherArr;
        return cell;
        
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return 181;
        
    }else if (indexPath.section == 1) {
        
//        return (71 + (SCREEN_WIDTH / 2 - 6) * 0.55) * 2;
        
        if (self.courseArr.count % 2 == 0) {
            return (71 + (SCREEN_WIDTH / 2 - 6) * 0.55) *self.courseArr.count/2;

        }
        else {
            return (71 + (SCREEN_WIDTH / 2 - 6) * 0.55) * (self.courseArr.count/2+1);

        }

    }else if (indexPath.section == 2) {
        
        return SCREEN_WIDTH * 0.41;
        
    }else {
        
        return 107;
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YYECourseApplyViewController *applyVC = [[YYECourseApplyViewController alloc]init];
    applyVC.model = self.faceArr[indexPath.row];
    [self.navigationController pushViewController:applyVC animated:YES];
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:titleLabel];
    
    UIImageView *leftIV = [[UIImageView alloc]init];
    [contentView addSubview:leftIV];
    
    UIImageView *rightIV = [[UIImageView alloc]init];
    [contentView addSubview:rightIV];
    
    UIButton *moreBtn = [[UIButton alloc]init];
    [contentView addSubview:moreBtn];
    
    [titleLabel makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(contentView.centerX);
        make.centerY.equalTo(contentView.centerY);
    }];
    
    [leftIV makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(titleLabel.left).offset(-10);
        make.centerY.equalTo(contentView.centerY);
        make.size.equalTo(CGSizeMake(27, 10));
    }];
    
    [rightIV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.right).offset(10);
        make.centerY.equalTo(contentView.centerY);
        make.size.equalTo(CGSizeMake(27, 10));
    }];
    
    [moreBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(contentView.right).offset(-10);
        make.centerY.equalTo(contentView.centerY);
        make.size.equalTo(CGSizeMake(20, 16));
    }];
    
    if (section == 0) {
        
        
        
    }else if (section == 1) {
        
        titleLabel.text = @"热门单课推荐";
        leftIV.image = [UIImage imageNamed:@"courseLeft"];
        rightIV.image = [UIImage imageNamed:@"courseRight"];
        [moreBtn setBackgroundImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
        [moreBtn addTarget:self action:@selector(hotCourseClicked) forControlEvents:UIControlEventTouchUpInside];
        
    }else if (section == 2) {
        
        titleLabel.text = @"最新面授课推荐";
        leftIV.image = [UIImage imageNamed:@"recommandLeft"];
        rightIV.image = [UIImage imageNamed:@"recommandRight"];
        [moreBtn setBackgroundImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
        [moreBtn addTarget:self action:@selector(latestCourseClicked) forControlEvents:UIControlEventTouchUpInside];
        
    }else {
        
        titleLabel.text = @"优质教师展示";
        leftIV.image = [UIImage imageNamed:@"teacherLeft"];
        rightIV.image = [UIImage imageNamed:@"teacherRight"];
        
    }
    
    return contentView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
//    return 30;
    if (section == 0) {
        return 0.01;
    }else {
        return 30;
    }
    
}

// 不让section头部停留
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 30;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

// 更多最新面授课
- (void)latestCourseClicked {
    
    YYELatestCourseViewController *courseVC = [[YYELatestCourseViewController alloc]init];
    [self.navigationController pushViewController:courseVC animated:YES];
    
}

// 热门单课推荐
- (void)hotCourseClicked {
    
    YYEHotCourseViewController *hotVC = [[YYEHotCourseViewController alloc]init];
    [self.navigationController pushViewController:hotVC animated:YES];
    
}

- (void)tapClicked {
    
    [self.view endEditing:YES];
//    NSArray *hotArr = @[@"Java", @"Python", @"Objective-C", @"Swift", @"C", @"C++", @"PHP", @"C#", @"Perl", @"Go", @"JavaScript", @"R", @"Ruby", @"MATLAB"];
    self.searchVC = [PYSearchViewController searchViewControllerWithHotSearches:self.hotArr searchBarPlaceholder:@"请输入关键词" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
//        [self.searchVC.navigationController pushViewController:[[YYECourseViewController alloc]init] animated:YES];
    }];
    
    for (UIView *subView in [[self.searchVC.searchBar.subviews lastObject] subviews]) {
        if ([[subView class] isSubclassOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)subView;
            textField.font = [UIFont systemFontOfSize:16];
            textField.layer.cornerRadius = 15;
            textField.clipsToBounds = YES;
            break;
        }
    }
    
    self.searchVC.hotSearchHeader.textColor = [UIColor blackColor];
    self.searchVC.delegate = self;
    self.searchVC.dataSource = self;
    [self.searchVC.cancelButton setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    self.searchVC.hotSearchStyle = PYHotSearchStyleDefault;
    self.searchVC.searchHistoryStyle = PYSearchHistoryStyleDefault;
    
    YYENaivigationController *navi = [[YYENaivigationController alloc]initWithRootViewController:self.searchVC];
    [self presentViewController:navi animated:YES completion:nil];
    
}


#pragma mark -- PYSearch
// 点击热门搜索
- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectHotSearchAtIndex:(NSInteger)index searchText:(NSString *)searchText {
    
    YYECourseSearchViewController *courseVC = [[YYECourseSearchViewController alloc]init];
    courseVC.searchText = searchText;
    [self.navigationController pushViewController:courseVC animated:YES];
    
    [self.searchVC dismissViewControllerAnimated:YES completion:nil];
}

// 点击历史搜索
- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectSearchHistoryAtIndex:(NSInteger)index searchText:(NSString *)searchText {
    
    YYECourseSearchViewController *courseVC = [[YYECourseSearchViewController alloc]init];
    courseVC.searchText = searchText;
    [self.navigationController pushViewController:courseVC animated:YES];
    
    [self.searchVC dismissViewControllerAnimated:YES completion:nil];
}

- (void)searchViewController:(PYSearchViewController *)searchViewController didSelectSearchSuggestionAtIndexPath:(NSIndexPath *)indexPath searchBar:(UISearchBar *)searchBar {
    
    NSLog(@"789");
    
}

// 内容修改
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)searchBar searchText:(NSString *)searchText{
    
    NSLog(@"111");
    
}

// 点击搜索
- (void)searchViewController:(PYSearchViewController *)searchViewController didSearchWithSearchBar:(UISearchBar *)searchBar searchText:(NSString *)searchText {
    
    NSLog(@"222");

    YYECourseSearchViewController *courseVC = [[YYECourseSearchViewController alloc]init];
    courseVC.searchText = searchText;
    [self.navigationController pushViewController:courseVC animated:YES];
    
    [self.searchVC dismissViewControllerAnimated:YES completion:nil];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
